/**
 * 
 */
package sg.edu.nus.iss.vmcs.payment;

import java.util.Observable;

import sg.edu.nus.iss.vmcs.system.Fault;
import sg.edu.nus.iss.vmcs.system.FaultObserver;
import sg.edu.nus.iss.vmcs.system.FaultType;
import sg.edu.nus.iss.vmcs.util.Log;

/**
 * @author moe
 * 
 */
public class NetsReader implements FaultObserver {
	NetsPayment ctrl = null;
	private Boolean hasFault = false;

	public NetsReader(NetsPayment ctrl) {
		this.ctrl = ctrl;
		Fault.getInstance().addObserver(this);
	}

	public void acceptCard() {
		Log.LogIt("NetsReader.acceptCard()");
		if (hasFault) {
			this.setActive(false);
		} else {
			this.setActive(true);
		}
		ctrl.getPaymentController().getPanel().getNetsUI().showEject(false);
	}

	public void ejectCard() {
		Log.LogIt("NetsReader.ejectCard()");
		ctrl.getPaymentController().getPanel().getNetsUI().showEject(true);
	}

	public void cardInserted() {
		NetsCardInfo info = new NetsCardInfo();
		info.setInfo("Accept Card");
		ctrl.getCardInfo(info);
	}

	public void rejectCard() {
		NetsCardInfo info = new NetsCardInfo();
		info.setInfo("Reject Card");
	}

	public void setActive(boolean b) {
		ctrl.getPaymentController().getPanel().getNetsUI().setActive(b);
	}

	public void cardCollected() {
		ctrl.getPaymentController().getPanel().getNetsUI().showEject(false);
		ctrl.getPaymentController().restartPayment();
	}

	public void setNetsError(boolean err) {
		if (err) {
			Fault.getInstance().setState(FaultType.NetsFault);
		} else {
			Fault.getInstance().clearFault(FaultType.NetsFault);
		}
		
		ctrl.getPaymentController().getPanel().getNetsUI().setProblemButton(err);
		ctrl.getPaymentController().getPanel().getNetsUI().setActive(false);
	}
	
	public void checkError(){
		Fault fault = Fault.getInstance();
		if (fault.hasFault(FaultType.NetsFault)){
			setActive(false);
		}
	}

	Fault fault = null;
	public void observeFault(Fault fault) {
		Log.LogIt("NetsReader.ObserveFault" + fault.getState());
		fault.addObserver(this);
		this.fault = fault;
		
	}

	public void update(Observable o, Object arg1) {
		Log.LogIt("NetsReader.update");
		boolean active = false;
		FaultType faultType = ((Fault) o).getState();
		Log.LogIt("CoinReceiver.update(" + faultType + ")");
		switch (faultType) {
		case CoinReceiverFault:
			// Nothing to do
			break;
		case DispenseFault:
			// Disable the Nets
			break;
		case NetsFault:
			break;
		case NO_FAULT:
			// Enable the Nets
			active = true;
			break;
		default:
			// Disable the Nets
			active = false;
			break;
		}
		setActive(false);
		ejectCard();
		Log.LogIt("Nets.update:setActive(" + active + ")");
	}

}
